<template>
  <div>
    <el-card style="overflow:visible;">
      <el-form :model="form" :rules="rules" size="mini" label-position="top" ref="form">
        <el-row :gutter="10">
          <el-col :lg="4" :md="6">
            <el-form-item label="机构">
              <!-- <select-tree v-model.trim="form.BRANCHNO" :props='{id: "BRANCHNO",label: "BRANCHNAME",children: "children"}'
                :tree-data="treedata" :node-key="'BRANCHNO'" :single-check="true"></select-tree> -->
              <select-tree :tree-data="treedata" :branch="form.BRANCHNAME" @getBranchName="getBranch"></select-tree>
            </el-form-item>
          </el-col>
          <el-col :lg="4" :md="6">
            <el-form-item label="坐席编号" prop="AGENTID">
              <el-input v-model.trim="form.AGENTID" placeholder="请输入用户编号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :lg="4" :md="6">
            <el-form-item label="坐席名称" prop="AGENTNAME">
              <el-input v-model.trim="form.AGENTNAME" placeholder="请输入用户名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :lg='12' :md='12' class="searchBtnMarginTop">
            <el-button type="primary" icon='el-icon-search' @click="checkUserList" size='mini'>查询
            </el-button>
          <!-- </el-col>
          <el-col :lg="2" :md="3" class="searchBtnMarginTop"> -->
            <el-button type='warning' size='mini' icon='el-icon-refresh' @click="resetForm('form')">重置</el-button>
          <!-- </el-col>
          <el-col :lg="2" :md="3" v-if="btnPermission('Button_User_Add')"  class="searchBtnMarginTop"> -->
          <!-- <el-button type="primary" size="mini" @click="createUser" icon='el-icon-plus'>新增用户</el-button> -->
        </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card style="margin-top:10px;">
      <el-table :data="tableData" ref="table" class="tableMarginTop" highlight-current-row
       style="min-height:390px;">
        <el-table-column prop="AGENTID" label="坐席编号" align="center">
        </el-table-column>
        <el-table-column prop="AGENTNAME" label="坐席名称"></el-table-column>
        <el-table-column prop="BRANCHNO" label="所在机构号" align="center"></el-table-column>
        <el-table-column prop="AGENTLEVEL" label="坐席等级" align="center"></el-table-column>
        <el-table-column prop="STATUS" label="人员状态" :formatter="statusFormat"></el-table-column>
        <el-table-column prop="GENDER" label="性别" align="center">
          <template slot-scope="scope">
              <span v-if="scope.row.GENDER==='1'">男</span>            
              <span v-else>女</span>            
          </template>
        </el-table-column>
        <el-table-column prop="TELPHONE" label="联系电话" width="100" align="center"></el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" content="修改" placement="top">
              <el-button type="text" style="margin-left:0px">
                <i class="el-icon-edit-outline"></i>
              </el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="删除" placement="top">
              <el-button type="text" style="margin-left:0px" @click="delUser(scope.row)">
                <i class="el-icon-delete"></i>
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <div style="text-align:right;margin-top:20px;" v-show="this.tableData">
        <el-pagination style="text-align: right; margin-top:20px;" 
          :page-sizes="[10, 20, 50, 100]" 
          :page-size="pageSize" 
          @size-change="handleInSizeChange" 
          @current-change="handleInCurrentChange" 
          :current-page="currpage" 
          background layout="sizes, total, prev, pager, next, jumper" 
          :total="tableTotal">
        </el-pagination>
      </div>
    </el-card>
    <!-- 弹窗 -->
    <!-- <keep-alive>
      <component :is="dialogList.CreateUser" :option="dialogOptions" @refreshTable="checkUserList"></component>
    </keep-alive>
     <keep-alive>
      <component :is="dialogList.systemMaintenceDialog" :option="dialogOptionsSystem"   @systemEmit="checkUserList"></component>
    </keep-alive> 
     <keep-alive>
      <component :is="dialogList.userRoleDialog" :option="dialogOptionsUserRole" ></component>
    </keep-alive> 
    <keep-alive>
      <component :is="dialogList.updateUser" :optionUpdate="dialogOptionsupdateUser"  @refreshTable="checkUserList"></component>
    </keep-alive>  -->
  </div>
</template>

<script>
  import selectTree from "@/components/selectTree5/";
  import request from "@/common/utils/requestWFM";
  import getGlobalParams from "@/common/utils/getGlobalParams";
  import userQuery from '@/message/wfm/baseData/userManage/userQuery';
  import Query from '@/message/wfm/baseData/branchManage/branchQuery'
  import { mapGetters } from "vuex";
  export default {
    computed: {
    ...mapGetters([
      "permission_routers",
      "UserName",
      "BranchName",
      "branchNo",
    ])
  },
    name: "user-info-manage",
    components: {
      selectTree
    },
    data() {
      return {
        userState: {}, //用户状态
        tableTotal: 1,
        currpage: 1,
        pageSize: getGlobalParams.get("PageSize"),
        brnoList: [], //机构下拉列表数据
        checkedIds: [], //机构下拉框V-model数据
        form: { //表单数据
          AGENTID: "",
          AGENTNAME: "",
          BRANCHNO: this.$store.getters.BranchNum,
          BRANCHNAME: this.$store.getters.BranchName,
        },
        rules: {
          BRANCHNO: [{
            required: true,
            message: '请选择机构',
            trigger: 'blur'
          }],
        },
        currentRow: [], //表格当前选中行
        tableData: [], //表格 数据
        dialogList: { //指定被渲染组件列表
          // CreateUser,
          // systemMaintenceDialog,
          // userRoleDialog,
          // updateUser
        },
        dialogOptions: { //创建用户
          isShow: false
        },
        dialogOptionsSystem: { //用户所属系统
          isShow: false,
          system: [],
          userId: "",
          clearRow: false
        },
        dialogOptionsUserRole: { //用户关联角色
          isShow: false,
          roleIdList: [],
          systemIdList: [],
          userId: ""
        },
        dialogOptionsupdateUser: {
          isShow: false,
          currentRow: []
        }, //修改用户
        loading: false, //loading遮罩
        startDialogVisible: false,
        checkedUser: false, //控制按钮是否可用
        isDisabledDel: false,
        resData: "",
        treedata: [],
        // 机构
        defaultProps: {
          children: 'children',
          label: 'BRANCHNAME'
        },
      };
    },
    computed: {
    },
    created() { //初始化下拉框
      this.userState = getGlobalParams.get("userState"); //用户状态初始化
      this.pageSize = getGlobalParams.get("PageSize");
    },
    mounted(){
      this.checkUserList();
      // this.queryBranch();
    },
    methods: {
      getBranch(data){
        this.form.BRANCHNO = data.BRANCHNO;
        this.form.BRANCHNAME = data.BRANCHNAME;
      },
      statusFormat(row, column) {
        if (row.STATUS == "01") {
          return "试用";
        } else if (row.Status == "02") {
          return "正式上岗";
        } else {
          return "";
        }
      },
       //前端分页
      handleInCurrentChange(val) {
        this.currpage = val;
        this.checkUserList();
      },
      handleInSizeChange(val) {
        this.pageSize = val;
        this.checkUserList();
      },
      delUser() { //删除弹出
        // this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        //   confirmButtonText: "确定",
        //   cancelButtonText: "取消",
        //   type: "warning"
        // })
        //   .then(() => {
        //     this.userDel();
        //   })
        //   .catch(() => {
        //     this.$message({
        //       type: "info",
        //       message: "已取消删除"
        //     });
        //   });
      },
      dataFormat(row, column) { //格式化表格
        //枚举设备形式
        return this.userState[row[column.property]];
      },
      resetForm(formName) { //重置查询表单
        this.$refs["" + formName].resetFields();
      },
      createUser() { //改变创建用户的显示状态
        this.dialogOptions.isShow = true;
      },
      // systemUser() { //设置打开用户系统页面所需的一些数据
      //   this.dialogOptionsSystem.isShow = true;
      //   this.dialogOptionsSystem.system = Object.assign(
      //     [],
      //     this.currentRow.systemIdList
      //   );
      //   this.dialogOptionsSystem.userId = this.currentRow.UserID;
      //   this.dialogOptionsSystem.clearRow = true;
      // },
      // modUser() { //修改用户
      //   this.dialogOptionsupdateUser.isShow = true;
      //   this.dialogOptionsupdateUser.currentRow = this.currentRow;
      // },
      userDel() { //删除用户
        this.loading = true;
        let resBody = new userDel();
        resBody.data.userId = this.currentRow.UserID;
        request(resBody)
          .then(response => {
            if (response.SYS_HEAD.ReturnCode === "000000") {
              this.loading = false;
              this.$message({
                type: "success",
                message: "用户删除成功!"
              });
              this.checkUserList();
            } else {
              this.loading = false;
              this.$message({
                type: "success",
                message: "用户删除失败!"
              });
            }
          })
          .catch(error => {
            this.loading = false;
          });
      },
      // roleMaintenance() { //设置打开用户关联角色页面所需的一些数据
      //   this.dialogOptionsUserRole.isShow = true;
      //   this.dialogOptionsUserRole.roleIdList = Object.assign(
      //     [],
      //     this.currentRow.roleIdList
      //   );
      //   this.dialogOptionsUserRole.systemIdList = Object.assign(
      //     [],
      //     this.currentRow.systemIdList
      //   );
      //   this.dialogOptionsUserRole.userId = this.currentRow.UserID;
      // },
      // 查询机构
      // async queryBranch() {
      //   let resBody = new Query()
      //   resBody.data.BRANCHNO = '';
      //   let response = await request(resBody);
      //   if (response.SYS_HEAD.ReturnCode == "000000") {
      //     this.resData = response.BODY.BRANCHDATA;
      //     this.toJson();
      //   } else {
      //     this.$message({
      //       type: "error",
      //       message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
      //     })
      //   }
      // },
      // toJson() {
      //   let _this = this;
      //   Array.prototype.ToTreeJson = function (pid) {
      //     var result = [],
      //       temp;
      //     for (var i in this) {
      //       if (this[i].FATHERBRANCHID == pid) {
      //         // console.log("this", this[i]);
      //         result.push(this[i]);
      //         temp = _this.circlefn(this, this[i].BRANCHID);
      //         if (temp.length > 0) {
      //           this[i].children = temp;
      //         }
      //       }
      //     }
      //     return result;
      //   }
      //   this.treedata = this.resData.ToTreeJson('0');
      // },
      // circlefn(data, pid) {
      //   var result = [],
      //     temp;
      //   for (var i in data) {
      //     if (data[i].FATHERBRANCHID == pid) {
      //       result.push(data[i]);
      //       temp = this.circlefn(data, data[i].BRANCHID);
      //       if (temp.length > 0) {
      //         data[i].children = temp;
      //       }
      //     }
      //   }
      //   return result;
      // },
      checkUserList() { //查询用户表格
        this.$refs['form'].validate((valid) => {
          if (valid) {
            this.tableData = [];
            this.checkedUser = false;
            this.isDisabledDel = false;
            this.loading = true;
            let resBody = new userQuery();
            resBody.data.AGENTID = this.form.AGENTID;
            resBody.data.AGENTNAME = this.form.AGENTNAME;
            resBody.data.BRANCHNO = this.form.BRANCHNO;
            resBody.data.CurrPage = this.currpage; 
            resBody.data.PageRowNum = this.pageSize;
            request(resBody)
              .then(response => {
                if (response.SYS_HEAD.ReturnCode === "000000") {
                  this.loading = false;
                  this.tableData = response.BODY.AGENTDATA;
                  this.tableTotal = response.BODY.TotalRowNum;
                }else{
                  this.$message({
                    type: "error",
                    message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
                  })
                }
              })
              .catch(error => {
                this.loading = false;
              });
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      // handleCurrentChange(val) { //表格选中行改变事件设置当前行的值（currentRow）已经改变控制按钮是否可用
      //   this.currentRow = val[0];
      //   if (val.length == 1) {
      //     this.checkedUser = true;
      //     this.isDisabledDel = true;
      //   } else if (val.length > 1) {
      //     this.checkedUser = false;
      //     this.isDisabledDel = true;
      //   } else {
      //     this.checkedUser = false;
      //     this.isDisabledDel = false;
      //   }
      // },

      /**
       * @desc 手动重置密码
       */
      handleResetPassword() {
        this.$confirm("此操作将重置此用户密码为‘123456’, 是否继续?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
          .then(() => {
            this.resetPassword();
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消重置"
            });
          });
      },

      /**
       * @desc 重置密码通讯方法
       * @param userId
       */
      resetPassword() {
        this.loading = true;
        let resBody = new resetPassword();
        resBody.data.userId = this.currentRow.UserID;
        request(resBody)
          .then(response => {
            if (response.SYS_HEAD.ReturnCode === "000000") {
              this.loading = false;
              this.$message({
                type: "success",
                message: "密码重置成功"
              });
            } else {
              this.loading = false;
              this.$message({
                type: "success",
                message: "密码重置失败"
              });
            }
          })
          .catch(error => {
            this.loading = false;
          });
      }
    }
  };

</script>


<style lang="scss" scoped>
  .selectTree {
    min-width: 150px;
  }

  .text {
    font-size: 14px;
  }

  .item {
    margin-bottom: 18px;
  }

  .dialog-text {
    display: inline-block;
    width: 100%;
    text-align: center;
    color: red;
    color:#081E45
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }

  .clearfix:after {
    clear: both;
  }

  .el-card {
    width: 100%;
  }

  .el-form-item {
    margin-left: 30px;
  }

  .el-form-item1 {
    margin-left: 10px;
  }

  .box2-button {
    width: 80px;
  }

  .el-card {
    overflow: inherit;
  }

</style>
